import {
  logout,
  getInfo
} from '@/pages/map/api/login';
import {
  getToken,
  setToken,
  removeToken
} from '@/pages/map/utils/auth';
import {
  getUserInfo
} from '@/pages/map/api/user';

const user = {
  state: {
    avatar: '',
    id: '2',
    password: '',
    username: '',
    caption: '',
    role: '',
    orgid: '2',
    organization: {}
  },

  mutations: {
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_PASSWORD: (state, password) => {
      state.password = password;
    },
    SET_USERNAME: (state, username) => {
      state.username = username;
    },
    SET_CAPTION: (state, caption) => {
      state.caption = caption;
    },
    SET_ROLE: (state, role) => {
      state.role = role;
    },
    SET_ORGANIZATION: (state, organization) => {
      state.organization = organization;
    }
  },

  actions: {

    /* 获取用户信息 */
    GetUserInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          const data = JSON.parse(response.datas);
          commit('SET_AVATAR', data.icon);
          commit('SET_ROLE', data.role_names);
          commit('SET_ID', data.id);
          commit('SET_PASSWORD', data.password);
          commit('SET_USERNAME', data.username);
          commit('SET_CAPTION', data.usercaption);
          commit('SET_ORGANIZATION', data.organization);
          resolve(response);
        }).catch(error => {
          // location.replace(bus.casUrl+'/log?service=' + bus.baseUrl);
          reject(error);
          window.location.reload();
        });
      });
    },
    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_AVATAR', '');
          commit('SET_ROLE', '');
          commit('SET_ID', '');
          commit('SET_PASSWORD', '');
          commit('SET_USERNAME', '');
          commit('SET_CAPTION', '');
          commit('SET_ORGANIZATION', {});
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    }
  }
};

export default user;
